package com.neuedu.autosale.purchase.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.neuedu.autosale.entity.Pager;
import com.neuedu.autosale.entity.Result;
import com.neuedu.autosale.purchase.entity.Stock;
import com.neuedu.autosale.purchase.service.StockService;
import com.neuedu.autosale.sys.entity.Provider;
import com.neuedu.autosale.sys.entity.Storage;

@Controller
public class StockController {
	@Autowired
	private StockService stockService;

	@RequestMapping("stock/index")
	public String stockIndex() {
		return "stock/stocklist";
	}

	@RequestMapping("stock/stocklist")
	@ResponseBody
	public Pager<Stock> stockList(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer rows, HttpServletRequest request) {
		String carName = request.getParameter("carName");
		String providerId = request.getParameter("providerId");
		String storageId = request.getParameter("storageId");

		System.out.println(carName + providerId + storageId);

		Pager<Stock> pager = new Pager<Stock>(page, rows);

		Stock stock = new Stock();

		if (carName != null && carName != "") {
			stock.setCarName(carName);
			pager.setCondition(stock);
		}

		if (providerId != null && providerId != "") {
			Provider provider = new Provider(providerId);
			stock.setProvider(provider);
			pager.setCondition(stock);
		}

		if (storageId != null && storageId != "") {
			Storage storage = new Storage(storageId);
			stock.setStorage(storage);
			pager.setCondition(stock);
		}

		List<Stock> stocklist = stockService.findListByPager(pager);
		int total = stockService.findTotalByPager(pager);

		System.out.println(stocklist.toString());

		pager.setRows(stocklist);
		pager.setTotal(total);
		return pager;
	}

	@RequestMapping("stock/add")
	@ResponseBody
	public Result doAdd(MultipartFile imageFile, Stock stock) {

		Result result = stockService.add(stock);
		return result;
	}

	@RequestMapping("stock/edit")
	@ResponseBody
	public Result doEdit(MultipartFile imageFile, Stock stock) {

		Result result = stockService.edit(stock);
		return result;
	}

	@RequestMapping("stock/delete")
	@ResponseBody
	public Result doDelete(Integer stockId) {
		List<Stock> list = new ArrayList<Stock>();
		list.add(new Stock(stockId));
		Result result = stockService.deleteByIds(list);
		return result;
	}

}
